package kayao.client.network.message;

import kayao.client.data.MissionHandler;
import kayao.client.network.SynchronizedTime;
import kayao.common.KayaoValues;
import kayao.common.NetworkUtils;

public class MissionMessage extends Message{
	
	private static int mLastMessageId=0;
	private static final int RETRIES = 0;
	private static final int TIMEOUT_LENGTH_MILLIS = 1000;
	private static final int PRIORITY = PRIORITY_MEDIUM;
	
	public MissionMessage(String targetAddress, boolean ack) {
		super(targetAddress, RETRIES, TIMEOUT_LENGTH_MILLIS, PRIORITY);
		if(ack)
			createAckPacketData();
		else
			createPacketData();
	}
	
	// Create a flag collision packet to server
	@Override
	public void createPacketData() {
		// Magic number (int32) + FLAG_COLLISION (b) + ID_MISSION (int32) + timestamp (int32) = 13 bytes
		mSendData = new byte[13];
		int index = 0;

		// Insert magic number (int32)
		NetworkUtils.insertIntToByteArray(mSendData, index, KayaoValues.MAGIC_NUMBER);
		index += 4;
		// Insert message id (b)
		mSendData[index] = KayaoValues.FLAG_COLLISION;
		index++;
		//Insert mission ID
		NetworkUtils.insertIntToByteArray(mSendData, index, MissionHandler.getMissionId());
		index += 4;
		//Insert time stamp
		NetworkUtils.insertIntToByteArray(mSendData, index, SynchronizedTime.getTime());
		index += 4;
		
	}

	// Create an ack to server
	public void createAckPacketData() {
		// Magic number (int32) + NEW_MISSION (b) + ID_MISSION (int32) = 9 bytes
		mSendData = new byte[9];
		int index = 0;

		// Insert magic number (int32)
		NetworkUtils.insertIntToByteArray(mSendData, index, KayaoValues.MAGIC_NUMBER);
		index += 4;
		// Insert message id (b)
		mSendData[index] = KayaoValues.NEW_MISSION;
		index++;
		//Insert mission ID
		NetworkUtils.insertIntToByteArray(mSendData, index, MissionHandler.getMissionId());
		index += 4;
		
	}
	
	public static void processPacket(byte[] receiveData){
//		[ MAGIC NUMBER (int32) | NEW_MISSION (b) | ID_MISSION (int32) | X (float) | Y (float) |Z (float) ]
		int index = 5;	// Magic number + Message ID already used

		int missionId = NetworkUtils.insertByteArrayToInt(receiveData, index);
		index+=4;
		
		float posX = NetworkUtils.insertByteArrayToFloat(receiveData, index);
		index+=4;
		float posY = NetworkUtils.insertByteArrayToFloat(receiveData, index);
		index+=4;
		float posZ = NetworkUtils.insertByteArrayToFloat(receiveData, index);
		index+=4;
		
		MissionHandler.newMission(missionId, posX, posY, posZ);
	}

	@Override
	public String type() {
		return "Mission";
	}

}
